package cn.dravenxiaokai.excel;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.IOException;

public class PoiReadExcel {
    /**
     * POI解析Excel
     * @param args
     * @author xiaokai
     * @date 2019-10-15 09:45:51
     */
    public static void main(String[] args) {
        // 需要解析的Excel文件
        File file  = new File("d:/output/poi_test.xls");
        try {
            // 创建Excel，读取文件内容
            HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file));
            // 获取第一个工作表
//            HSSFSheet sheet = workbook.getSheet("sheet0");
            // 读取默认第一个工作表
            HSSFSheet sheet = workbook.getSheetAt(0);
            int firstRowNum = 0;
            // 获取sheet中最后一行行号
            int lastRowNum = sheet.getLastRowNum();
            for(int i=0;i<lastRowNum;i++){
                HSSFRow row = sheet.getRow(i);
                int lastCellNum = row.getLastCellNum();
                for(int j=0;j<lastCellNum;j++){
                    HSSFCell cell = row.getCell(j);
                    String value = cell.getStringCellValue();
                    System.out.print(value+" ");
                }
                System.out.println();
            }
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
